package com.radiant.data.entity.converter;

import org.apache.commons.beanutils.Converter;

import com.radiant.data.annotation.PreProcessor;
import com.radiant.data.entity.GenericDAO;
import com.radiant.exceptions.RadiantRuntimeException;

public class SimpleDBEntityConverter<T extends GenericDAO<?>> implements Converter {

	private PreProcessor preProcessor;

	private T entityDAO;

	public SimpleDBEntityConverter(PreProcessor preProcessor, T entityDAO) {
		this.preProcessor = preProcessor;
		this.entityDAO = entityDAO;
	}

	public Object convert(Class type, Object value) {
		if (type == String.class) {
			try {
				return preProcessor.getItemReadMethod(value.getClass()).invoke(value, new Object[]{});
			} catch (Exception e) {
				throw new RadiantRuntimeException("Error convering SimpleDBEntity to string form", e);
			}
		} else if (type == entityDAO.getPersistentClass()) {
			return entityDAO.findByPrimaryKey((String)value, false);
		}
		return value;
	}

	
}
